/*
 * WandToolView.java
 */

package wandtool;

import com.surelution.core.drivers.CommunicationException;
import com.surelution.core.drivers.Connection;
import com.surelution.core.drivers.DriverFactory;
import com.surelution.core.drivers.Wand;
import com.surelution.core.drivers.kh_v2.KhLibrary;
import java.awt.Color;
import java.io.IOException;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * The application's main frame.
 */
public class WandToolView extends FrameView {

    public WandToolView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = WandToolApp.getApplication().getMainFrame();
            aboutBox = new WandToolAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        WandToolApp.getApplication().show(aboutBox);
    }
    private Wand wand;          

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLWandSnInfo = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTNewName = new javax.swing.JTextField();
        jBSubmit = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(wandtool.WandToolApp.class).getContext().getResourceMap(WandToolView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btReadInfoActionPerformed(evt);
            }
        });

        jLWandSnInfo.setText(resourceMap.getString("jLWandSnInfo.text")); // NOI18N
        jLWandSnInfo.setName("jLWandSnInfo"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jTNewName.setText(resourceMap.getString("jTNewName.text")); // NOI18N
        jTNewName.setName("jTNewName"); // NOI18N

        jBSubmit.setText(resourceMap.getString("jBSubmit.text")); // NOI18N
        jBSubmit.setName("jBSubmit"); // NOI18N
        jBSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSumbitAction(evt);
            }
        });

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(73, 73, 73)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTNewName, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29)
                        .addComponent(jBSubmit))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(137, 137, 137)
                        .addComponent(jButton1))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(jLabel1))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addComponent(jLWandSnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(147, 147, 147)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(51, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jButton1)
                .addGap(10, 10, 10)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jLWandSnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTNewName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jBSubmit)))
                .addGap(18, 18, 18)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(44, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(wandtool.WandToolApp.class).getContext().getActionMap(WandToolView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setIcon(resourceMap.getIcon("exitMenuItem.icon")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 380, Short.MAX_VALUE)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void btReadInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReadInfoActionPerformed
        Properties prop = new Properties();
        prop.put("type", KhLibrary.MT_USB);
        prop.put("baut", 460800);
        Connection conn;
        System.out.println("connectDevice...");
        try {
            conn = DriverFactory.buildConnection("com.surelution.core.drivers.kh_v2.KhConnection", prop );
            System.out.println("conn:"+conn);
            wand = conn.prepareWand();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
        }            
            this.jLWandSnInfo.setForeground(Color.black);
            this.jLWandSnInfo.setText("正在连接设备...");

        String wandSn = wand.getId();
        System.out.println("Connecting success,Now start to verify device...");
        System.out.println(wandSn);
        this.jLWandSnInfo.setForeground(Color.red);       
        this.jLWandSnInfo.setText("巡检棒编号为" + wandSn + "，但因服务器连接失败，无法验证！");

        //verify
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        StringBuilder query = new StringBuilder("http://localhost:8080/tour");
        query.append("/clientGate/shakeHands?wandSn=");
        query.append(wandSn);
        query.append("&terminalTime=");
            try {
                query.append(sdf.format(wand.getTime()));
            } catch (CommunicationException ex) {
                Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
            }
            query.append("&stationTime=");
            query.append(sdf.format(new Date()));
            System.out.println(query.toString());
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(query.toString());
            try {
                HttpResponse response = client.execute(get);
                InputStream is = response.getEntity().getContent();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder;
                builder = factory.newDocumentBuilder();
                Document doc;
                doc = builder.parse(is);
                doc.getDocumentElement().normalize();
                NodeList nodeList = doc.getElementsByTagName("code");
                if(nodeList != null) {
                    Node codeNode = nodeList.item(0);
                    String code = codeNode.getTextContent();
                    System.out.println("start to verify!");
                    if("FOUND-WAND".contains(code)) {
                        String user = doc.getElementsByTagName("user").item(0).getTextContent();
                        System.out.println("巡检棒序号：" + wandSn + " 使用者：" + user);
                        this.jLWandSnInfo.setText("巡检棒序号：" + wandSn + " 使用者：" + user);       
                        this.jLWandSnInfo.setForeground(Color.black);       
                    }
                    else {
                        System.out.println("巡检棒编号为" +wandSn);
                        this.jLWandSnInfo.setForeground(Color.red);       
                        this.jLWandSnInfo.setText("巡检棒编号为" + wandSn + "，但未进行指派！");       
                    }
                }

            } catch (SAXException ex) {
                Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
            }
            // TODO add your handling code here:
    }//GEN-LAST:event_btReadInfoActionPerformed

    private void jBSumbitAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSumbitAction
        System.out.println("setid");
        Properties prop = new Properties();
        prop.put("type", KhLibrary.MT_USB);
        prop.put("baut", 460800);
        Connection conn;
        try {
            conn = DriverFactory.buildConnection("com.surelution.core.drivers.kh_v2.KhConnection", prop );
            System.out.println("conn:"+conn);
            wand = conn.prepareWand();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(WandToolView.class.getName()).log(Level.SEVERE, null, ex);
        }
        String id =jTNewName.getText();
        System.out.println(id);
        if(id != null && id.length() == 4) {
            try {
                int v = Integer.parseInt(id, 16);
                System.out.println("v:" + v);
                if(v >= 0 && v < 65535) {
                    wand.setId(id);
                    System.out.println("wandsn:" + wand.getId());
                    this.jLabel3.setText("设置成功");
                    this.jLabel3.setForeground(Color.blue);
                }
		} catch(NumberFormatException e) {
                    System.out.println("请输入四位十六进制！");
                    this.jLabel3.setText("请输入四位十六进制！");
                    this.jLabel3.setForeground(Color.red);
                }
        }
        else {
                System.out.println("请输入四位十六进制！");
                this.jLabel3.setText("请输入四位十六进制！");
                this.jLabel3.setForeground(Color.red);
        }
        System.out.println("Finish");
        // TODO add your handling code here:
    }//GEN-LAST:event_jBSumbitAction

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBSubmit;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLWandSnInfo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTNewName;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}
